#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <time.h>
#include <sys/ioctl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//server
int main()
{
	int server_sock,client_sock;
	struct sockaddr_in server_addr,client_addr;
	int server_len,client_len;
	int result;
	fd_set readfds,testfds;

	server_sock = socket(AF_INET,SOCK_STREAM,0);

	server_addr.sin_family = AF_INET;
	server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	server_addr.sin_port = htons(9000);
	bzero(&(server_addr.sin_zero),8);//将整个结构剩余部分数据设为0
	server_len = sizeof(server_addr);

	bind(server_sock,(struct sockaddr *)&server_addr,server_len);

	listen(server_sock,5);
	FD_ZERO(&readfds);
	FD_SET(server_sock,&readfds);
	while(1)
	{
		int fd,nread;
		
		testfds = readfds;
		printf("server waiting...\n");

		result = select(FD_SETSIZE,&testfds,(fd_set *)0,(fd_set *)0,(struct timeval *)0);	
		if(result < 1)
		{
			perror("server error:");
			exit(0);
		}
		
		for (fd = 0;fd < FD_SETSIZE;fd++)
		{
			if(FD_ISSET(fd,&testfds))
			{
				if(fd == server_sock)
				{
				  client_len = sizeof(client_addr);
				  client_sock = accept(server_sock,(struct sockaddr *)&client_addr,(socklen_t *)client_len);
				  FD_SET(client_sock,&readfds);
				  printf("add  client on fd %d\n",client_sock);
				}
				else
				{
					ioctl(fd,FIONREAD,&nread);
					if(nread == 0)
					{
						close(fd);
						FD_CLR(fd,&readfds);
						printf("remove client on fd %d\n",fd);
					}
					else
					{
						write(fd,"hello",5);
					}
				}
			}
		}
	}
}
